#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# cron: 30 22 * * *
# new Env("小米任务每日统计")

import os
import re
import glob
import logging
import requests
from datetime import datetime, timedelta
from collections import defaultdict

# 配置日志格式
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger("XiaoMiStats")

# ====================== 配置区域 ======================
LOG_DIR_PATTERN = "/ql/data/log/XiaoMao_小米*"  # 支持通配符匹配小米相关日志
TIME_RANGE_HOURS = 24  # 分析最近多少小时的日志
DEBUG_MODE = False      # 设置为True启用详细调试日志
REPORT_FILE = "/ql/data/log/Message/PUSH_XIAOMI.log"  # 报告保存路径
VIDEO_EXCHANGE_THRESHOLD = 30  # 可兑换视频账号阈值（天）
# =====================================================

# 在logger定义后设置调试模式
if DEBUG_MODE:
    logger.setLevel(logging.DEBUG)
    logger.debug("调试模式已启用")

def clean_error_message(message):
    """清理错误消息，移除技术细节"""
    # 移除所有JSON代码和Python错误消息
    message = re.sub(r"\{.*?\}", "", message)  # 移除JSON代码
    message = re.sub(r"'[^']*'", "", message)  # 移除单引号内容
    message = re.sub(r"\d+", "", message)  # 移除数字
    message = re.sub(r"\s+", " ", message)  # 合并多余空格
    
    # 移除特定技术短语
    tech_phrases = [
        "object is not subscriptable",
        "NoneType",
        "AttributeError",
        "TypeError",
        "ValueError",
        "KeyError",
        "JSONDecodeError"
    ]
    for phrase in tech_phrases:
        message = message.replace(phrase, "")
    
    # 移除前缀和标点
    prefixes = ["执行异常", "⚠️", "❌"]
    for prefix in prefixes:
        if message.startswith(prefix):
            message = message[len(prefix):].strip()
    
    # 移除尾部冒号
    if message.endswith(":") or message.endswith("："):
        message = message[:-1].strip()
    
    # 提取核心错误描述
    if ":" in message:
        message = message.split(":", 1)[0].strip()
    if "：" in message:
        message = message.split("：", 1)[0].strip()
    
    return message.strip()

def parse_xiaomi_logs(log_content, account_data):
    """
    解析小米任务日志内容并提取统计信息
    """
    # 编译正则表达式
    account_pattern = re.compile(r'ℹ️\s*账号\s*\d+/\d+:\s*(\d+)')
    wallet_account_pattern = re.compile(r'>>>>>>>>>>\s*正在处理账号\s*(\d+)')
    account_id_pattern = re.compile(r'✨\s*账号ID[:：]\s*(\d+)')  # 新增账号ID识别
    growth_pattern = re.compile(r'✅\s*\d+\s*完成\s*\|\s*(.*?)\s*成长值:\s*(\d+)')
    sign_success_pattern = re.compile(r'ℹ️\s*(每日签到|微信小程序签到)\s*(已完成|success)')
    sign_fail_pattern = re.compile(r'❌\s*(每日签到|微信小程序签到)\s*失败[：:]\s*(.+)')
    task_completed_pattern = re.compile(r'✅\s*([^:]+):\s*(ok|success)')
    task_fail_pattern = re.compile(r'❌\s*([^:]+)\s*失败[：:]\s*(.+)')
    video_days_pattern = re.compile(r'📊\s*当前兑换视频天数[:：]?\s*([\d.]+)天')
    video_reward_pattern = re.compile(r'🎁\s*领到视频会员[，,]\s*\+([\d.]+)天')
    wallet_error_pattern = re.compile(r'⚠️\s*执行异常[:：]\s*(.+)')
    
    current_account = None
    lines = log_content.split('\n')
    
    for line in lines:
        # 宽松处理空行
        if not line.strip():
            continue
            
        # 调试日志：打印处理的行
        logger.debug(f"处理行: {line}")
            
        # 检测账号 - 社区格式
        account_match = account_pattern.search(line)
        if account_match:
            current_account = account_match.group(1)
            if current_account not in account_data:
                account_data[current_account] = {
                    'growth': 0,
                    'video_days': 0.0,
                    'today_video': 0.0,  # 新增：当天获得的视频天数
                    'sign_in': False,
                    'mini_sign': False,
                    'sign_fail_reason': None,
                    'completed_tasks': [],
                    'failed_tasks': [],
                    'video_rewards': [],
                    'wallet_errors': [],
                    'account_type': '未知',
                    'exchangeable': False
                }
            logger.debug(f"检测到社区账号: {current_account}")
            continue
            
        # 检测账号 - 钱包格式
        wallet_account_match = wallet_account_pattern.search(line)
        if wallet_account_match:
            current_account = wallet_account_match.group(1)
            if current_account not in account_data:
                account_data[current_account] = {
                    'growth': 0,
                    'video_days': 0.0,
                    'today_video': 0.0,  # 新增：当天获得的视频天数
                    'sign_in': False,
                    'mini_sign': False,
                    'sign_fail_reason': None,
                    'completed_tasks': [],
                    'failed_tasks': [],
                    'video_rewards': [],
                    'wallet_errors': [],
                    'account_type': '未知',
                    'exchangeable': False
                }
            logger.debug(f"检测到钱包账号: {current_account}")
            continue
            
        # 检测账号 - 账号ID格式 (新增)
        account_id_match = account_id_pattern.search(line)
        if account_id_match:
            current_account = account_id_match.group(1)
            if current_account not in account_data:
                account_data[current_account] = {
                    'growth': 0,
                    'video_days': 0.0,
                    'today_video': 0.0,  # 新增：当天获得的视频天数
                    'sign_in': False,
                    'mini_sign': False,
                    'sign_fail_reason': None,
                    'completed_tasks': [],
                    'failed_tasks': [],
                    'video_rewards': [],
                    'wallet_errors': [],
                    'account_type': '未知',
                    'exchangeable': False
                }
            logger.debug(f"检测到账号ID: {current_account}")
            continue
            
        if not current_account:
            continue
            
        # 提取成长值信息
        growth_match = growth_pattern.search(line)
        if growth_match:
            account_type = growth_match.group(1).strip()
            growth = int(growth_match.group(2))
            account_data[current_account]['growth'] = growth
            account_data[current_account]['account_type'] = account_type
            logger.debug(f"{current_account} 成长值: {growth} | 类型: {account_type}")
            continue
            
        # 提取视频天数信息 - 修复匹配逻辑
        video_days_match = video_days_pattern.search(line)
        if video_days_match:
            try:
                video_days = float(video_days_match.group(1))
                account_data[current_account]['video_days'] = video_days
                
                # 检查是否可兑换
                if video_days > VIDEO_EXCHANGE_THRESHOLD:
                    account_data[current_account]['exchangeable'] = True
                    logger.info(f"🎁 发现可兑换账号: {current_account} ({video_days}天)")
                
                logger.debug(f"{current_account} 视频天数: {video_days}")
            except ValueError:
                logger.warning(f"无法解析视频天数: {line}")
            continue
            
        # 提取签到成功
        sign_success_match = sign_success_pattern.search(line)
        if sign_success_match:
            sign_type = sign_success_match.group(1)
            if sign_type == "每日签到":
                account_data[current_account]['sign_in'] = True
                logger.debug(f"{current_account} 每日签到成功")
            elif sign_type == "微信小程序签到":
                account_data[current_account]['mini_sign'] = True
                logger.debug(f"{current_account} 小程序签到成功")
            continue
            
        # 提取签到失败
        sign_fail_match = sign_fail_pattern.search(line)
        if sign_fail_match:
            sign_type = sign_fail_match.group(1)
            reason = sign_fail_match.group(2).strip()
            if sign_type == "每日签到":
                account_data[current_account]['sign_fail_reason'] = reason
            account_data[current_account]['wallet_errors'].append({
                'type': 'sign_fail',
                'message': f"{sign_type}失败: {reason}",
                'account': current_account
            })
            logger.debug(f"{current_account} {sign_type}失败: {reason}")
            continue
            
        # 提取任务成功
        task_completed_match = task_completed_pattern.search(line)
        if task_completed_match:
            task_name = task_completed_match.group(1).strip()
            if task_name not in account_data[current_account]['completed_tasks']:
                account_data[current_account]['completed_tasks'].append(task_name)
            logger.debug(f"{current_account} 任务[{task_name}]成功")
            continue
            
        # 提取任务失败
        task_fail_match = task_fail_pattern.search(line)
        if task_fail_match:
            task_name = task_fail_match.group(1).strip()
            reason = task_fail_match.group(2).strip()
            if task_name not in account_data[current_account]['failed_tasks']:
                account_data[current_account]['failed_tasks'].append(task_name)
            account_data[current_account]['wallet_errors'].append({
                'type': 'task_fail',
                'message': f"{task_name}失败: {reason}",
                'account': current_account
            })
            logger.debug(f"{current_account} 任务[{task_name}]失败: {reason}")
            continue
            
        # 提取视频奖励 - 修复逻辑
        video_reward_match = video_reward_pattern.search(line)
        if video_reward_match:
            try:
                reward = float(video_reward_match.group(1))
                account_data[current_account]['video_rewards'].append(reward)
                
                # 新增：累加当天获得的视频天数
                account_data[current_account]['today_video'] += reward
                
                logger.debug(f"{current_account} 获得视频奖励: +{reward}天")
            except ValueError:
                logger.warning(f"无法解析视频奖励: {line}")
            continue
            
        # 提取钱包错误
        wallet_error_match = wallet_error_pattern.search(line)
        if wallet_error_match:
            error = wallet_error_match.group(1).strip()
            account_data[current_account]['wallet_errors'].append({
                'type': 'wallet_error',
                'message': error,
                'account': current_account
            })
            logger.debug(f"{current_account} 钱包错误: {error}")
            continue
    
    return account_data

def process_log_directories():
    """
    处理日志目录并解析所有匹配的日志文件
    返回账号统计数据
    """
    # 计算时间范围（最近N小时）
    time_threshold = datetime.now() - timedelta(hours=TIME_RANGE_HOURS)
    logger.info(f"分析时间范围: {time_threshold.strftime('%Y-%m-%d %H:%M:%S')} 至今")
    
    account_data = {}
    processed_files = 0
    skipped_files = 0
    
    # 获取所有匹配的日志文件（按时间倒序）
    all_files = []
    for log_dir in glob.glob(LOG_DIR_PATTERN):
        if not os.path.isdir(log_dir):
            continue
            
        for filename in os.listdir(log_dir):
            if filename.endswith('.log'):
                file_path = os.path.join(log_dir, filename)
                if not os.path.exists(file_path):
                    continue
                try:
                    file_mtime = datetime.fromtimestamp(os.path.getmtime(file_path))
                    all_files.append((file_path, file_mtime))
                except Exception as e:
                    logger.error(f"获取文件修改时间失败: {file_path} - {str(e)}")
    
    # 按修改时间倒序排序
    all_files.sort(key=lambda x: x[1], reverse=True)
    
    # 处理日志文件
    for file_path, file_mtime in all_files:
        if file_mtime < time_threshold:
            skipped_files += 1
            logger.debug(f"跳过旧文件: {os.path.basename(file_path)} - {file_mtime}")
            continue
            
        try:
            logger.info(f"分析文件: {os.path.basename(file_path)}")
            with open(file_path, 'r', encoding='utf-8') as f:
                content = f.read()
                account_data = parse_xiaomi_logs(content, account_data)
                processed_files += 1
                
                # 检查数据完整性 - 如果有账号数据，继续处理更多文件
                if account_data:
                    logger.info(f"已找到 {len(account_data)} 个账号数据")
                    
        except Exception as e:
            logger.error(f"文件解析失败: {file_path} - {str(e)}")
    
    logger.info(f"文件处理完成: 已处理 {processed_files} 个文件, 跳过 {skipped_files} 个")
    return account_data

def generate_table_report(account_data):
    """生成表格格式的统计报告"""
    if not account_data:
        return "⚠️ 未找到有效的账号统计信息", {}
    
    # 计算总计
    totals = {
        'growth': 0,
        'video_days': 0.0,
        'sign_success': 0,
        'mini_sign_success': 0,
        'sign_fail': 0,
        'exchangeable_count': 0,
        'exchangeable_accounts': [],
        'video_rewards': 0.0,
        'today_video': 0.0,  # 新增：当天获得视频天数总计
        'completed_tasks': defaultdict(int),
        'failed_tasks': defaultdict(int),
        'wallet_errors': [],
        'accounts': len(account_data)
    }
    
    # 构建表格报告
    report_lines = [
        "📊 小米任务每日统计报告",
        "=" * 60,
        "📈 全局汇总:"
    ]
    
    # 添加全局汇总信息
    report_lines.append(f"    👥 总账号数: {len(account_data)}个")
    
    # 计算成长值总计
    total_growth = sum(data['growth'] for data in account_data.values())
    totals['growth'] = total_growth
    report_lines.append(f"    📈 总成长值: {total_growth}")
    
    # 计算视频天数总计（所有账号的总视频天数）
    total_video_days = sum(data.get('video_days', 0.0) for data in account_data.values())
    totals['video_days'] = total_video_days
    report_lines.append(f"    📺 当前总视频天数: {total_video_days:.2f}天")
    
    # 计算签到情况
    sign_success = sum(1 for data in account_data.values() if data.get('sign_in', False))
    mini_sign_success = sum(1 for data in account_data.values() if data.get('mini_sign', False))
    sign_fail = sum(1 for data in account_data.values() if data.get('sign_fail_reason'))
    totals['sign_success'] = sign_success
    totals['mini_sign_success'] = mini_sign_success
    totals['sign_fail'] = sign_fail
    
    report_lines.append(f"    ✅ 每日签到成功: {sign_success}个")
    report_lines.append(f"    📱 小程序签到成功: {mini_sign_success}个")
    report_lines.append(f"    ❌ 签到失败: {sign_fail}个")
    
    # 计算当日视频奖励
    total_today_video = sum(data.get('today_video', 0.0) for data in account_data.values())
    totals['today_video'] = total_today_video
    report_lines.append(f"    🎁 今日获得视频天数: {total_today_video:.2f}天")
    
    # 计算可兑换视频账号
    exchangeable_count = 0
    exchangeable_accounts = []
    for account, data in account_data.items():
        if data.get('video_days', 0.0) > VIDEO_EXCHANGE_THRESHOLD:
            exchangeable_count += 1
            exchangeable_accounts.append(account)
    
    totals['exchangeable_count'] = exchangeable_count
    totals['exchangeable_accounts'] = exchangeable_accounts
    
    # 添加可兑换视频账号信息
    report_lines.append(f"    💡 可兑换视频账号 (> {VIDEO_EXCHANGE_THRESHOLD}天): {exchangeable_count}个")
    
    # 如果有可兑换账号，显示具体账号
    if exchangeable_count > 0:
        report_lines.append(f"        账号: {', '.join(exchangeable_accounts)}")
    
    # 收集所有错误
    for account, data in account_data.items():
        for error in data.get('wallet_errors', []):
            totals['wallet_errors'].append(error)
    
    # 添加错误统计
    report_lines.append(f"    ⚠️ 错误总数: {len(totals['wallet_errors'])}个")
    
    # 计算任务统计
    for data in account_data.values():
        for task in data.get('completed_tasks', []):
            totals['completed_tasks'][task] += 1
        for task in data.get('failed_tasks', []):
            totals['failed_tasks'][task] += 1
    
    # 添加任务汇总
    if totals['completed_tasks']:
        report_lines.append("\n    📌 任务完成情况:")
        for task, count in totals['completed_tasks'].items():
            report_lines.append(f"        ✅ {task}: {count}/{len(account_data)}")
    
    if totals['failed_tasks']:
        report_lines.append("\n    ⚠️ 任务失败情况:")
        for task, count in totals['failed_tasks'].items():
            report_lines.append(f"        ❌ {task}: {count}/{len(account_data)}")
    
    report_lines.append("=" * 60)
    report_lines.append("\n📋 账号详情:")
    
    # 添加表格标题
    report_lines.append("\n账    号".ljust(20) + "类型".center(10) + "成长值".center(10) + 
                       "总可兑换天数".center(12) + "当天获得天数".center(12) + "签到".center(10) + "任务".center(10))
    report_lines.append("─" * 80)
    
    # 添加每个账号的信息
    for account, data in account_data.items():
        # 格式化账号信息
        account_display = f"🔷 {account}"
        
        # 格式化账号类型
        account_type = data.get('account_type', '未知')[:4]
        account_type_display = account_type.center(10)
        
        # 格式化成长值
        growth_value = data.get('growth', 0)
        growth_display = f"{growth_value}".center(10)
        
        # 格式化总可兑换天数
        video_days = data.get('video_days', 0.0)
        video_days_display = f"{video_days:.2f}".center(12)
        
        # 格式化当天获得天数 (使用新增的today_video字段)
        today_rewards = data.get('today_video', 0.0)
        today_rewards_display = f"{today_rewards:.2f}".center(12)
        
        # 格式化签到
        sign_in = data.get('sign_in', False)
        mini_sign = data.get('mini_sign', False)
        sign_display = ""
        if sign_in:
            sign_display += "✅"
        if mini_sign:
            sign_display += "📱"
        if not sign_in and not mini_sign:
            sign_display = "❌"
        if data.get('sign_fail_reason'):
            sign_display = "❌"
        sign_display = sign_display.center(10)
        
        # 格式化任务
        completed = len(data.get('completed_tasks', []))
        failed = len(data.get('failed_tasks', []))
        task_total = completed + failed
        task_display = f"{completed}/{task_total}" if task_total > 0 else "0/0"
        task_display = task_display.center(10)
        
        # 添加账号行
        report_lines.append(
            account_display.ljust(20) + 
            account_type_display + 
            growth_display + 
            video_days_display + 
            today_rewards_display + 
            sign_display + 
            task_display
        )
        
        # 添加分隔线
        report_lines.append("─" * 80)
    
    # 添加错误汇总（使用清理后的错误消息）
    if totals['wallet_errors']:
        report_lines.append("\n⚠️ 错误汇总:")
        # 按错误类型分组
        error_groups = defaultdict(list)
        for error in totals['wallet_errors']:
            # 清理错误消息
            clean_msg = clean_error_message(error['message'])
            error_groups[clean_msg].append(error['account'])
        
        for error_msg, accounts in error_groups.items():
            report_lines.append(f"    {error_msg}")
            report_lines.append(f"        账号: {', '.join(accounts)}")
    
    # 添加报告时间
    report_lines.append("=" * 60)
    report_lines.append(f"📅 报告生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    
    return "\n".join(report_lines), totals

def push_plus_notify(title, content):
    """
    使用PUSH_PLUS推送通知
    """
    token = os.environ.get('PUSH_PLUS_TOKEN')
    if not token:
        logger.error("未找到PUSH_PLUS_TOKEN环境变量，无法发送通知")
        return False
    
    try:
        # PUSH_PLUS API地址
        url = "http://www.pushplus.plus/send"
        
        # 请求数据
        data = {
            "token": token,
            "title": title,
            "content": content,
            "template": "txt"
        }
        
        # 发送请求
        response = requests.post(url, json=data)
        result = response.json()
        
        if response.status_code == 200 and result.get("code") == 200:
            logger.info("PUSH_PLUS通知发送成功")
            return True
        else:
            logger.error(f"PUSH_PLUS通知发送失败: {result.get('msg', '未知错误')}")
            return False
    except Exception as e:
        logger.error(f"发送PUSH_PLUS通知时出错: {str(e)}")
        return False

def send_notification(title, content):
    """
    发送通知
    """
    # 使用PUSH_PLUS发送通知
    if push_plus_notify(title, content):
        return True
    
    logger.warning("PUSH_PLUS通知发送失败，尝试使用其他通知方式")
    # 这里可以添加其他通知方式，如sendNotify.js
    return False

def main():
    """主函数"""
    task_start = datetime.now()
    logger.info("开始小米任务每日统计")
    
    try:
        # 步骤1: 处理日志目录
        account_data = process_log_directories()
        
        # 步骤2: 生成报告
        report, totals = generate_table_report(account_data)
        
        # 步骤3: 输出报告
        logger.info("\n" + report)
        
        # 步骤4: 保存报告到文件
        os.makedirs(os.path.dirname(REPORT_FILE), exist_ok=True)
        with open(REPORT_FILE, 'w', encoding='utf-8') as f:
            f.write(report)
        logger.info(f"统计报告已保存至: {REPORT_FILE}")
        
        # 步骤5: 发送通知（包含完整账号详情）
        if account_data:
            # 创建通知标题
            title = f"小米任务每日统计 ({len(account_data)}账号)"
            
            # 创建通知内容
            notify_content = [
                "📊 小米任务每日统计报告",
                "=" * 40,
                "📈 全局汇总:",
                f"    👥 总账号数: {len(account_data)}个",
                f"    📈 总成长值: {totals['growth']}",
                f"    📺 当前总视频天数: {totals['video_days']:.2f}天",
                f"    ✅ 每日签到成功: {totals['sign_success']}个",
                f"    📱 小程序签到成功: {totals['mini_sign_success']}个",
                f"    ❌ 签到失败: {totals['sign_fail']}个",
                f"    🎁 今日获得视频天数: {totals['today_video']:.2f}天",
                f"    💡 可兑换视频账号 (> {VIDEO_EXCHANGE_THRESHOLD}天): {totals['exchangeable_count']}个",
                f"    ⚠️ 错误总数: {len(totals['wallet_errors'])}个"
            ]
            
            # 添加可兑换视频账号信息
            if totals['exchangeable_count'] > 0:
                notify_content.append(f"        账号: {', '.join(totals['exchangeable_accounts'])}")
            
            notify_content.append("=" * 40)
            notify_content.append("\n📋 账号详情 (完整):")
            
            # 添加表格标题
            notify_content.append("\n账    号".ljust(15) + "类型".center(6) + "成长值".center(6) + 
                                "总天数".center(8) + "当天获得".center(8) + "签到".center(6) + "任务".center(6))
            notify_content.append("─" * 50)
            
            # 添加每个账号的信息（完整显示）
            for account, data in account_data.items():
                # 格式化账号信息
                account_display = account
                
                # 格式化账号类型
                account_type = data.get('account_type', '未知')[:4]
                account_type_display = account_type.center(6)
                
                # 格式化成长值
                growth_value = data.get('growth', 0)
                growth_display = f"{growth_value}".center(6)
                
                # 格式化总可兑换天数
                video_days = data.get('video_days', 0.0)
                video_days_display = f"{video_days:.2f}".center(8)  # 确保两位小数
                
                # 格式化当天获得天数
                today_rewards = data.get('today_video', 0.0)
                today_rewards_display = f"{today_rewards:.2f}".center(8)  # 确保两位小数
                
                # 格式化签到
                sign_in = data.get('sign_in', False)
                mini_sign = data.get('mini_sign', False)
                sign_display = ""
                if sign_in:
                    sign_display += "✅"
                if mini_sign:
                    sign_display += "📱"
                if not sign_in and not mini_sign:
                    sign_display = "❌"
                sign_display = sign_display.center(6)
                
                # 格式化任务
                completed = len(data.get('completed_tasks', []))
                failed = len(data.get('failed_tasks', []))
                task_total = completed + failed
                task_display = f"{completed}/{task_total}" if task_total > 0 else "0/0"
                task_display = task_display.center(6)
                
                # 添加账号行
                notify_content.append(
                    account_display.ljust(15) + 
                    account_type_display + 
                    growth_display + 
                    video_days_display + 
                    today_rewards_display + 
                    sign_display + 
                    task_display
                )
            
            # 添加错误汇总（使用清理后的错误消息）
            if totals['wallet_errors']:
                notify_content.append("\n⚠️ 错误汇总:")
                # 按错误类型分组
                error_groups = defaultdict(list)
                for error in totals['wallet_errors']:
                    # 清理错误消息
                    clean_msg = clean_error_message(error['message'])
                    error_groups[clean_msg].append(error['account'])
                
                for error_msg, accounts in error_groups.items():
                    notify_content.append(f"    {error_msg}")
                    notify_content.append(f"        账号: {', '.join(accounts)}")
            
            # 添加报告时间
            notify_content.append("=" * 40)
            notify_content.append(f"📅 报告生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
            
            # 发送通知
            send_notification(title, "\n".join(notify_content))
        else:
            logger.warning("无有效数据，跳过通知发送")
        
        # 计算任务耗时
        task_duration = datetime.now() - task_start
        logger.info(f"任务总耗时: {task_duration.total_seconds():.2f} 秒")
        
        # 返回退出码（0表示成功）
        return 0
    except Exception as e:
        logger.exception(f"任务执行失败: {str(e)}")
        # 发送错误通知
        error_title = "小米任务每日统计失败"
        error_content = f"任务执行出错: {str(e)}\n\n请查看日志获取详细信息"
        send_notification(error_title, error_content)
        return 1

if __name__ == "__main__":
    import sys
    from datetime import datetime
    
    # 设置时区为北京时间
    os.environ['TZ'] = 'Asia/Shanghai'
    
    exit_code = main()
    sys.exit(exit_code)